/**
 * There are <a href="https://github.com/thinkgem/jeesite">JeeSite</a> code generation
 */
package com.chlitina.store.modules.inventory.web;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.chlitina.store.common.config.Global;
import com.chlitina.store.common.mapper.JsonMapper;
import com.chlitina.store.common.persistence.Page;
import com.chlitina.store.common.web.BaseController;
import com.chlitina.store.modules.base.entity.StoreProduct;
import com.chlitina.store.modules.base.service.StoreProductService;
import com.chlitina.store.modules.employee.service.EmployeeService;
import com.chlitina.store.modules.inventory.entity.StoreInventoryCheck;
import com.chlitina.store.modules.inventory.entity.StoreInventoryCheckDetail;
import com.chlitina.store.modules.inventory.model.InventoryQuery;
import com.chlitina.store.modules.inventory.service.StoreInventoryCheckDetailService;
import com.chlitina.store.modules.inventory.service.StoreInventoryCheckService;
import com.chlitina.store.modules.inventory.utils.StoreInventoryUtils;
import com.chlitina.store.modules.sys.entity.Store;
import com.chlitina.store.modules.sys.utils.StoreUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;

/**
 * 库存盘点Controller
 * 
 * @author lvbo
 * @version 2013-11-18
 */
@Controller
@RequestMapping(value = Global.ADMIN_PATH + "/inventory/storeInventoryCheck")
public class StoreInventoryCheckController extends BaseController {

	@Autowired
	private StoreInventoryCheckService storeInventoryCheckService;
	@Autowired
	private StoreInventoryCheckDetailService storeInventoryCheckDetailService;
	@Autowired
	private StoreProductService storeProductService;
	@Autowired
	private EmployeeService employeeService;

	@ModelAttribute
	public StoreInventoryCheck get(@RequestParam(required = false) Long id) {
		if (id != null) {
			return storeInventoryCheckService.get(id);
		} else {
			return new StoreInventoryCheck();
		}
	}

	@ResponseBody
	@RequestMapping(value = { "selectProduct"})
	public String systemProductPage(StoreInventoryCheck storeInventoryCheck,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		response.setContentType("application/json; charset=UTF-8");
		HttpSession session = request.getSession();
		InventoryQuery inventoryQuery = new InventoryQuery();
		inventoryQuery = storeProductService.findStoreProducts(inventoryQuery);
		List<StoreProduct> allStoreProducts = inventoryQuery.getStoreProducts();
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session.getAttribute("checkScope");
		// 剔除列表中已存在的产品
		List<StoreProduct> storeProducts = Lists.newArrayList();
		if (spList != null) {
			model.addAttribute("productScopeList", spList);
			for (StoreProduct asp : allStoreProducts) {
				boolean isExsit = false;
				for (StoreProduct sp : spList) {
					if (sp.getId().equals(asp.getId())) {
						isExsit = true;
						break;
					}
				}
				if (!isExsit) {
					storeProducts.add(asp);
				}
			}
		}
		String type = request.getParameter("type");
		List<StoreProduct> productList = Lists.newArrayList();
		// 克丽缇娜产品
		if (StoreProduct.TYPE_SYS == Integer.parseInt(type)) {
			for (StoreProduct p : storeProducts) {
				if (p.getProduct_type() == StoreProduct.TYPE_SYS && p.getAmount() > 0) {
					productList.add(p);
				}
			}
		}
		// 店面自营产品
		if (StoreProduct.TYPE_SELF == Integer.parseInt(type)) {
			for (StoreProduct p : storeProducts) {
				if (p.getProduct_type() == StoreProduct.TYPE_SELF && p.getAmount() > 0) {
					productList.add(p);
				}
			}
		}
		Set<Map<String, Object>> set = Sets.newHashSet();
		for (StoreProduct p : productList) {
			Map<String, Object> map = Maps.newHashMap();
			map.put("id", p.getId());
			if (StoreProduct.TYPE_SELF == Integer.parseInt(type)) {
				map.put("name", p.getStoreSelfProduct().getName());
			}
			if (StoreProduct.TYPE_SYS == Integer.parseInt(type)) {
				map.put("name", p.getProduct().getName());
			}
			set.add(map);
		}
		return JsonMapper.getInstance().toJson(set);
	}

	@RequestMapping(value = "saveProduct")
	public String saveProduct(HttpServletRequest request, HttpServletResponse response,
			Model model){
		HttpSession session = request.getSession();
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session
				.getAttribute("checkScope");
		List<StoreProduct> checkScopeList = Lists.newLinkedList();
		if (spList == null) {
			spList = checkScopeList;
			session.setAttribute("checkScope", spList);
		}
		String productIds = request.getParameter("productIds");
		if (productIds != null) {
			String[] idArrs = productIds.split(",");
			for (String productId : idArrs) {
				boolean isSelected = isSelectProduct(Long.parseLong(productId),
						spList);
				StoreProduct storeProduct = storeProductService.get(Long
						.parseLong(productId));
				if (!isSelected) {
					spList.add(storeProduct);
				}
			}
		}
		session.setAttribute("checkScope", spList);
		return "redirect:" + Global.ADMIN_PATH
				+ "/inventory/storeInventoryCheck/detailList";
	}
	
	@RequestMapping(value = { "list", "" })
	public String list(StoreInventoryCheck storeInventoryCheck,
			HttpServletRequest request, HttpServletResponse response,
			Model model) {
		Store store = StoreUtils.getStore();
		if (store != null) {
			storeInventoryCheck.setStore(store);
		}
		HttpSession session = request.getSession();
		String startDate = request.getParameter("startDate");
		String endDate = request.getParameter("endDate");
		String oldStart = (String)session.getAttribute("startDate");
		String oldEnd = (String)session.getAttribute("endDate");
		startDate = startDate != null ? startDate : oldStart;
		endDate = endDate != null ? endDate : oldEnd;
		Page<StoreInventoryCheck> page = storeInventoryCheckService.find(
				new Page<StoreInventoryCheck>(request, response),
				storeInventoryCheck, startDate, endDate);
		session.setAttribute("startDate", startDate);
		session.setAttribute("endDate", endDate);
		model.addAttribute("page", page);
		return "modules/inventory/storeInventoryCheckList";
	}

	@RequestMapping(value = "detailList")
	public String saveScope(StoreInventoryCheck storeInventoryCheck,
			HttpServletRequest request, HttpServletResponse response,
			Model model, RedirectAttributes redirectAttributes) {
		HttpSession session = request.getSession();
		String employeeId = request.getParameter("eid");
		List<StoreProduct> checkScopeList = Lists.newLinkedList();
		if (employeeId != null) {
			session.setAttribute("checkScope", checkScopeList);
			session.setAttribute("eid", employeeId);
			return "modules/inventory/storeInventoryCheckDetailList";
		}
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session
				.getAttribute("checkScope");
		if (spList == null) {
			spList = checkScopeList;
			session.setAttribute("checkScope", spList);
		}
		session.setAttribute("checkScope", spList);
		String remark = (String) session.getAttribute("remark");
		if (remark != null) {
			model.addAttribute("remark", remark);
		}
		model.addAttribute("productScopeList", spList);
		return "modules/inventory/storeInventoryCheckDetailList";
	}
	
	@ResponseBody
	@RequestMapping(value = "updateRemark")
	public String updateRemark(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String remark = request.getParameter("remark");
		String oldRemark = (String) session.getAttribute("remark");
		if (remark != null && !"".equals(remark)) {
			if (oldRemark == null || !remark.equals(oldRemark)) {
				oldRemark = remark;
				session.setAttribute("remark", oldRemark);
			}
		}
		return "";
	}
	
	@ResponseBody
	@RequestMapping(value = "updateAmount")
	public String updateProductAmount(HttpServletRequest request) {
		HttpSession session = request.getSession();
		String productId = request.getParameter("productId");
		String amount = request.getParameter("amount");
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session.getAttribute("checkScope");
		if (spList != null) {
			for (StoreProduct storeProduct : spList) {
				if (storeProduct.getId().equals(Long.parseLong(productId))) {
					storeProduct.setAmount(Integer.parseInt(amount));
				}
			}
		}
		session.setAttribute("checkScope", spList);
		return "";
	}
	@RequestMapping(value = "cancel")
	public String cancel(HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		HttpSession session = request.getSession();
		session.removeAttribute("checkScope");
		session.removeAttribute("remark");
		session.removeAttribute("eid");
		return "redirect:" + Global.ADMIN_PATH
				+ "/inventory/storeInventoryCheck/";
	}

	@RequestMapping(value = "finish")
	public String finish(HttpServletRequest request,
			RedirectAttributes redirectAttributes) {
		HttpSession session = request.getSession();
		//创建并存入数据库
		//check
		String eid = (String)session.getAttribute("eid");
		String remark = (String)session.getAttribute("remark");
		StoreInventoryCheck check = new StoreInventoryCheck();
		check.setEmployee(employeeService.get(Long.parseLong(eid)));
		check.setCheckTime(new Date());
		check.setStore(StoreUtils.getStore());
		if (remark != null && !"".equals(remark)) {
			check.setRemark(remark);
		}
		storeInventoryCheckService.save(check);
		//check list
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session
				.getAttribute("checkScope");
		for (StoreProduct p : spList) {
			StoreInventoryCheckDetail checkDetail = new StoreInventoryCheckDetail();
			checkDetail.setStoreInventoryCheck(check);
			StoreProduct storeProduct = StoreInventoryUtils.getStoreProduct(p.getId());
			checkDetail.setStoreProduct(p);
			checkDetail.setBeforeAdjustAmount(storeProduct.getAmount());
			checkDetail.setAfterAdjustAmount(p.getAmount());
			if (p.getProduct_type() == StoreProduct.TYPE_SYS) {
				checkDetail.setSpec(p.getProduct().getSpec());
				checkDetail.setRetailPrice(p.getProduct().getRetail_price());
			} else if (p.getProduct_type() == StoreProduct.TYPE_SELF) {
				checkDetail.setSpec(p.getStoreSelfProduct().getSpec());
				checkDetail.setRetailPrice(p.getStoreSelfProduct()
						.getRetail_price());
			}
			float lossMoney = getLossMoney(checkDetail);
			checkDetail.setLossMoney(lossMoney);
			storeProductService.save(p);
			storeInventoryCheckDetailService.save(checkDetail);
		}
		session.removeAttribute("checkScope");
		session.removeAttribute("remark");
		session.removeAttribute("eid");
		addMessage(redirectAttributes, "本次库存盘点操作已成功，产品库存数量已同步更新！");
		return "redirect:" + Global.ADMIN_PATH
				+ "/inventory/storeInventoryCheck/";
	}

	@ResponseBody
	@RequestMapping(value = "deleteProduct")
	public String deleteProduct(HttpServletRequest request,
			HttpServletResponse response,
			RedirectAttributes redirectAttributes, Model model) {
		HttpSession session = request.getSession();
		String productId = request.getParameter("productId");
		Long id = null;
		try {
			id = Long.parseLong(productId);
		} catch (Exception e) {
			return "";
		}
		@SuppressWarnings("unchecked")
		List<StoreProduct> spList = (List<StoreProduct>) session
				.getAttribute("checkScope");
		List<StoreProduct> finishList = Lists.newArrayList();
		for (StoreProduct storeProduct : spList) {
			if (!storeProduct.getId().equals(id)) {
				finishList.add(storeProduct);
			}
		}
		session.setAttribute("checkScope", finishList);
		return "";
	}

	@RequestMapping(value = "delete")
	public String delete(Long id, RedirectAttributes redirectAttributes) {
		storeInventoryCheckService.delete(id);
		addMessage(redirectAttributes, "删除库存盘点成功");
		return "redirect:" + Global.ADMIN_PATH
				+ "/inventory/storeInventoryCheck/";
	}
	
	public boolean isSelectProduct(Long productId, List<StoreProduct> spList) {
		boolean isSelected = false;
		for (StoreProduct sp : spList) {
			if (sp.getId().equals(productId)) {
				isSelected = true;
				break;
			}
		}
		return isSelected;
	}
	private float getLossMoney(StoreInventoryCheckDetail detail){
		int before = detail.getBeforeAdjustAmount();
		int after = detail.getAfterAdjustAmount();
		float retailPrice = detail.getRetailPrice();
		return  (before - after) * retailPrice;
	}
}
